-- SPDX-FileCopyrightText: Adam Evyčędo
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

function getUpdates(tripID, sequence, stopID, stopCode)
	local http = require("http")
	local json = require("json")

	error_struct = {
		httpResponseCode=0,
		message="",
		willNextRequestFail=false
	}

	response, error_message = http.get("https://stibmivb.opendatasoft.com/api/explore/v2.1/catalog/datasets/waiting-time-rt-production/records", {
    query="apikey={{.ApiKey}}&where=pointid%20%3D%20%22" .. stopID .. "%22&limit=20",
    timeout="30s"
  })

	if response == nil then
		error_struct.message = "while getting updates: " .. error_message
		error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	if response.status_code ~= 200 then
		error_struct.message = "api returned code " .. response.status_code .. "; " .. response.body
		error_struct.httpResponseCode = response.status_code
		error_struct.willNextRequestFail = true
		error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	struct, error_message = json.decode(response.body)

	if struct == nil then
		error_struct.message = "while decoding updates: " .. error_message
		error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	updates = {
		areTripsInTimetable=false,
		updates={}
	}
	updates.updates[''] = {
		time="000000",
		stopID=stopID,
		delay=0,
		timetableRelationship=1,
		vehicleStatus={
			lineName="",
			headsign=""
		}
	}


	for i,entry in ipairs(struct.results) do
		times, error_message = json.decode(entry.passingtimes)
		if times == nil then
			error_struct.message = "while decoding times for stop " .. entry.pointid .. ", line " .. entry.lineid .. ": " .. error_message
			error_json, _ = json.encode(error_struct)
			return "", error_json
		end

		for i, time_entry in ipairs(times) do
			if time_entry.destination ~= nil then
				updates.updates[time_entry.expectedArrivalTime] = {
					time=string.sub(time_entry.expectedArrivalTime, 12, 13) .. string.sub(time_entry.expectedArrivalTime, 15, 16) .. string.sub(time_entry.expectedArrivalTime, 18, 19),
					stopID=stopID,
					delay=0,
					timetableRelationship=1,
					vehicleStatus={
						lineName=entry.lineid,
						headsign=time_entry.destination.fr
					}
				}
			end
		end
	end

	result, error_message = json.encode(updates)

	if result == nil then
		error_struct.message = "while encoding result: " .. error_message
		error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	return result, ""
end
